package com.threez.single.admin.singleadmin.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.threez.single.admin.singleadmin.config.Constants;
import com.threez.single.admin.singleadmin.core.R;
import com.threez.single.admin.singleadmin.core.module.LoginUser;
import com.threez.single.admin.singleadmin.model.LoginForm;
import com.threez.single.admin.singleadmin.util.LoginHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhaozz
 * @title LoginController
 * @date 2023/3/2 9:23
 */
@Slf4j
@RestController
@RequestMapping("/auth-user")
public class LoginController {

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @SaIgnore
    @PostMapping("/login")
    public R<Map<String, Object>> login(@Validated @RequestBody LoginForm loginBody) {
        Map<String, Object> ajax = new HashMap<>();
        // 生成令牌
//        LambdaQueryWrapper<AuthUser> queryWrapper = new QueryWrapper<AuthUser>().lambda()
//                .eq(AuthUser::getUsername, loginBody.getUsername());
//
//        AuthUser user = iAuthUserService.getOne(queryWrapper);
//        if (ObjectUtil.isNull(user)) {
//            log.info("登录用户：{} 不存在.", loginBody.getUsername());
//            throw new BaseException("user.not.exists" + loginBody.getUsername());
//        } else if (UserStatus.DISABLE.getCode().equals(user.getIsStaff())) {
//            log.info("登录用户：{} 已被停用.", loginBody.getUsername());
//            throw new BaseException("user.blocked" + loginBody.getUsername());
//        }
        LoginUser loginUser = new LoginUser();
//        loginUser.setId(user.getId());
//        loginUser.setUsername(user.getUsername());
        // 生成token
        LoginHelper.loginByDevice(loginUser);
        log.info("登录成功");
        ajax.put(Constants.TOKEN, StpUtil.getTokenValue());
        return R.ok(ajax);
    }
    /**
     * 退出登录
     */
    @SaIgnore
    @PostMapping("/logout")
    public R<Void> logout() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        log.info("当前登录用户退出登录：{}", loginUser.getUsername());
        StpUtil.logout();
        return R.ok("退出成功");
    }

    @PostMapping("/info")
    public R<LoginUser> getUserInfo() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        log.info("当前登录用户信息：{}", JSONObject.toJSONString(loginUser));
        return R.ok(loginUser);
    }
}
